import networkx as nx
import collections

class EmpNetworkConverter(object):

    @staticmethod
    def SaveEmpNetworkToGraphMl(empNetwork, path):
        graph = empNetwork.graph
        EmpNetworkConverter._AddNetworkFieldsToGraph(empNetwork)
        EmpNetworkConverter._AddAgentFieldsToGraph(empNetwork)
        
        nx.write_graphml(graph, path)
        
    @staticmethod
    def LoadEmpNetworkFromGraphMl(empNetwork, path):
            #see http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary
            pass
        
    @staticmethod
    def SaveEmpNetworkToGpickle(empNetwork, path):
        EmpNetworkConverter._AddNetworkFieldsToGraph(empNetwork)
        nx.write_gpickle(empNetwork.graph, path)

    @staticmethod
    def SaveEmpNetworkToGexf(empNetwork, path):
        graph = empNetwork.graph
        EmpNetworkConverter._AddNetworkFieldsToGraph(empNetwork)
        EmpNetworkConverter._AddAgentFieldsToGraph(empNetwork)

        nx.write_gexf(graph, path)

    @staticmethod
    def LoadEmpNetworkFromGexf(empNetwork, path):
            pass

    @staticmethod
    def _AddNetworkFieldsToGraph(network):
        for fieldName, fieldValue in network.__dict__.items():
            if fieldName == "graph" or fieldName == "agentList":
                continue
            if isinstance(fieldValue, collections.Iterable):
                fieldValue = str(fieldValue)
            network.graph.graph[fieldName] = fieldValue

    @staticmethod
    def _AddAgentFieldsToGraph(network):           
        for agent in network.agentList:
            for fieldName, fieldValue in agent.__dict__.items():
                if isinstance(fieldValue, collections.Iterable):
                    fieldValue = str(fieldValue)
                network.graph.node[agent][fieldName] = fieldValue

        
         